package com.guigu.auth.service.impl.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.auth.entity.AuthUser;
import com.guigu.auth.service.AuthUserService;
import com.guigu.commons.pojo.SecurityUser;
import com.guigu.tms.exception.TmsException;
import com.guigu.tms.result.ResultCode;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName:UserService
 * @Description://TODO
 * @Author:taoLong
 * @Date:2021/12/8:18:32 星期三
 * @email:2391611102@qq.com or 2391611102qq@gmail.com
 */
@Service
public class UserService implements UserDetailsService {
    @Autowired
    private AuthUserService authUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (StringUtils.isBlank(username)) {
            throw new TmsException(ResultCode.ERROR_CODE, "用户名不能为空!");
        }
        QueryWrapper<AuthUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", username);
        AuthUser user = authUserService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(user)) {
            throw new TmsException(ResultCode.ERROR_CODE, "用户名不存在!");
        }
        Set<String> permissions = new HashSet<>();
        permissions.add("admin");
        SecurityUser securityUser = new SecurityUser(user.getAccount(), user.getPassword(), permissions);
        securityUser.setAccount(user.getAccount());
        securityUser.setId(user.getId().toString());
        return securityUser;
    }
}
